package com.leadership.api.handler.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.demo2do.core.utils.JsonUtils;
import com.leadership.api.handler.IdmHandler;
import com.leadership.api.utils.IdmHttpRaoUtils;
import com.leadership.entity.idm.IdmOrg;
import com.leadership.entity.idm.IdmUser;
import com.leadership.entity.idm.WsUser;

/**
 * 
 * @author dan
 *
 */
@Component("idmHandler")
public class IdmHandlerImpl implements IdmHandler{
    
    private static final Logger logger = LoggerFactory.getLogger(IdmHandlerImpl.class);
    
    //private static final String orgUrl ="http://idmtest.cifi.com.cn:28080/sim/api/v2/org?filter=FILTER";
    
    //private static final String userUrl = "http://idmtest.cifi.com.cn:28080/sim/api/v2/user?filter=FILTER&pageSize=1000000";
    
    private static final String orgUrl ="http://sim.cifi.com.cn/sim/api/v2/org?filter=FILTER";
    
    private static final String userUrl = "http://sim.cifi.com.cn/sim/api/v2/user?filter=FILTER&pageSize=1000000";
    
    /*
     * (non-Javadoc)
     * @see com.leadership.api.handler.IdmHandler#listIdmOrg(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    public List<IdmOrg> listIdmOrg(String filter) throws UnsupportedEncodingException {

        List<IdmOrg> idmOrgs = new ArrayList<IdmOrg>();
        filter = URLEncoder.encode(filter, "UTF-8");
        String url = orgUrl.replace("FILTER", filter);

        String response = IdmHttpRaoUtils.doGet(url, null);
        Map<String, Object> result = JsonUtils.parse(response, Map.class);
        String code = (String) result.get("success");
        if(StringUtils.equalsIgnoreCase(code, "true")) {
            String body = JsonUtils.toJson(result.get("body"));
            String wsUserObject = body.substring(1, body.length()-1);
            
            if(StringUtils.isNotBlank(body)) {
                
                List<WsUser> wsUsers = JsonUtils.parseAsList(wsUserObject, WsUser.class);
                for(WsUser wsUser : wsUsers) {
                    IdmOrg idmOrg = new IdmOrg(wsUser.getAttrs());
                    idmOrgs.add(idmOrg);
                }
            }
        } else {
            logger.error("#listIdmOrg - call idm api failed, resultCode is " + result.get("resultCode"));
        }
        
        return idmOrgs;
    }
    
    /*
     * (non-Javadoc)
     * @see com.leadership.api.handler.IdmHandler#listIdmUser(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    public List<IdmUser> listIdmUser(String filter) {

        List<IdmUser> idmUsers = new ArrayList<IdmUser>();
          try {
              filter = URLEncoder.encode(filter, "UTF-8");
              String url = userUrl.replace("FILTER", filter);
              String response = IdmHttpRaoUtils.doGet(url, null);
              //logger.info("response is [{}]", response);
              Map<String, Object> result = JsonUtils.parse(response, Map.class);
              String code = (String) result.get("success");
//              logger.info("code is [{}]", code);
              if(StringUtils.equalsIgnoreCase(code, "true")) {
                  Map<String, Object> body = (Map<String, Object>) result.get("body");
                  
                  if(body != null && !body.isEmpty()) {
                      logger.info("has user");
                      String wsUserObject = JsonUtils.toJson(body.get("wsUsers"));
                      
                      List<WsUser> wsUsers = JsonUtils.parseAsList(wsUserObject, WsUser.class);
                      if(org.apache.commons.collections.CollectionUtils.isNotEmpty(wsUsers)) {
                          for(WsUser wsUser : wsUsers) {
                              IdmUser idmUser = new IdmUser(wsUser.getAttrs());
                              idmUsers.add(idmUser);
                          }
                      }
                  }
              } else {
                  logger.error("#listIdmUser - call idm api failed, resultCode is " + result.get("resultCode"));
              }
          } catch (Exception e) {
              logger.error("#listIdmUser - call idm api failed, ", e);
          }
            
        return idmUsers;
    }
}
